<template>
  <panel-head :route="route"/>
  <div class="btns">
    <el-button type="primary" @click="openStaffFormDialog(null)">新增</el-button>
    <el-button type="danger" @click="deleteStaff()">删除</el-button>
  </div>
  <!-- 添加陪护师弹窗 -->
  <el-dialog v-model="staffFormVisible" title="陪护师" width="500">
    <el-form 
    :model="staffForm"
    ref="staffFormRef"
    :rules="rules"
    :before-close="staffDialogBeforeClose">
      <el-form-item label="昵称" prop="name">
        <el-input v-model="staffForm.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-button type="primary" @click="avatarDialogVisible=true" v-if="!staffForm.avatar">更改头像</el-button>
          <el-image
            v-else
            :src="staffForm.avatar"
            style="width: 100px;height: 100px;"
          />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="staffForm.sex" placeholder="请选择性别">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="staffForm.age" :min="20" :max="40"/>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="staffForm.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="是否生效" prop="active">
       <div class="my-2 ml-4">
          <el-radio-group v-model="staffForm.active">
            <el-radio :value="0">失效</el-radio>
            <el-radio :value="1">生效</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitStaff(staffFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 选择头像弹窗 -->
  <el-dialog 
  v-model="avatarDialogVisible" 
  title="选择图片" 
  width="700"
  :before-close="avatarDialogBeforeClose">
    <div class="image-list">
      <div class="img-box" v-for="(avatar,index) in avatarList" :key="avatar.name" @click="avatarSelected=avatar.name">
        <div v-if="avatarSelected===avatar.name" class="select">
          <el-icon color="#fff"><Select /></el-icon>
        </div>
        <el-image 
        style="width: 148px; height: 148px" 
        :src="avatar.url"/>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="avatarDialogBeforeClose()">
            取消
        </el-button>
        <el-button type="primary" @click="submitAvatar()">
            确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 陪护师列表展示 -->
  <el-table 
  :data="tableData.list" 
  style="width: 100%"
  ref="tableRef"
  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="id"/>
      <el-table-column prop="name" label="昵称"/>
      <el-table-column prop="avatar" label="头像" >
        <template #default="scope">
           <img :src="scope.row.avatar" style="width: 50px;height: 50px;">
        </template>
      </el-table-column>
      <el-table-column  prop="sex" label="性别"  >
        <template #default="scope">
            {{scope.row.sex?'男':'女' }}
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="手机号" />
      <el-table-column prop="active" label="状态" >
        <template #default="scope">
             <el-tag type="success" v-show="scope.row.active===1">正常</el-tag>
             <el-tag type="danger" v-show="scope.row.active===0">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" >
        <template #default="scope">
          <div class="my-vertical-align">
            <el-icon><Clock /></el-icon>
            {{ dayjs(scope.row.create_time).format('YYYY-MM-DD') }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template #default="scope">
         <el-button type="primary" @click="openStaffFormDialog(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
  <!-- 分页 -->
 <div class="pagination-info">
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="paginationData.pageNum"
        :page-size="paginationData.pageSize"
        layout="total, prev, pager, next"
        :total="tableData.total"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  </template>
<script setup>
import {ref,reactive, onMounted, toRaw}from 'vue'
import {useRoute} from 'vue-router'
import {photoList,companion,companionList,deleteCompanion} from '../../../api'
import {ElMessage } from 'element-plus'
import dayjs from 'dayjs'
const route=useRoute()
dayjs().format()

//陪护师弹窗数据
const staffFormVisible=ref(false)
const staffFormRef=ref()
const staffForm=ref({
  id: '',
  mobile: '',
  active: 0,
  age: 0,
  avatar: '',
  name: '',
  sex: ''
})
//表单校验规则
const rules=reactive({
  name: [{ required: true, message: '请输入陪护师姓名', trigger: 'blur' },],
  avatar: [{ required: true, message: '请选择头像', trigger: 'blur' },],
  sex: [{ required: true, message: '请选择陪护师性别', trigger: 'blur' },],
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },],
})
//性别选择数据
const options=reactive([
  {
    value: '0',
    label: '女',
  },
  {
    value: '1',
    label: '男',
  }
])

//头像更改数据
const avatarDialogVisible=ref(false)
const avatarList=ref()
const avatarSelected=ref()

//分页数据
const paginationData=reactive({
  pageNum:1,
  pageSize:10
})
//陪护师列表数据
const tableData=ref({
  list:[],
  total:0
})
const tableRef=ref()
//被勾选的陪护师数据
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map((item)=>({id:item.id}))
}
//请求陪护师列表
const getStaffList=()=>{
  companionList(paginationData).then((data)=>{
    // console.log(data)
    tableData.value=data.data
  })
}

onMounted(()=>{
  //获取头像列表数据
  photoList().then((data)=>{
    // console.log(data)
    avatarList.value=data.data
  })},
  //获取陪护师列表数据
  getStaffList()
)

//打开陪护师弹窗
const openStaffFormDialog=(staffData)=>{
  if(staffData){
    //修改陪护师资料
    staffForm.value=staffData
  }
  staffFormVisible.value=true
}

//提交陪护师申请
const submitStaff= async (formEl)=>{
  //表单校验
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      companion(toRaw(staffForm.value)).then((data)=>{
        if(data.code===10000){
          ElMessage.success('陪护师创建成功!')
          staffDialogBeforeClose()
          //重新渲染陪护师列表
            getStaffList()
        }else{
          console.log(data)
          ElMessage.warning('陪护师创建失败，请稍后再试!')
        }
      })
    } else {
      console.log('error submit!', fields)
      ElMessage.warning('请校验数据')
    }
  })

}

//更改头像
const submitAvatar=()=>{
  const avaterObj=avatarList.value.find(element=>element.name===avatarSelected.value)
  staffForm.value.avatar=avaterObj.url
  avatarDialogBeforeClose()
}
//两个弹窗关闭回调
const avatarDialogBeforeClose=()=>{
  avatarSelected.value=''
  avatarDialogVisible.value=false
}
const staffDialogBeforeClose=()=>{
  staffFormVisible.value=false
  //重置表单
  staffFormRef.value.resetFields()
  // console.log(staffForm.value)
  // 重置表单数据（关键）
  staffForm.value = {
    id: '',
    mobile: '',
    active: 0,
    age: 0,
    avatar: '',
    name: '',
    sex: ''
  };
}
//处理分页方法
const handleCurrentChange=(val)=>{
  paginationData.pageNum=val
  //请求账号列表
  getStaffList()
}
//删除陪护师方法
const deleteStaff=()=>{
  deleteCompanion({id:multipleSelection.value}).then((data)=>{
    console.log(data)
    if(data.code===10000){
      ElMessage.success('删除成功！')
      //再次渲染列表
      getStaffList()
    }
  })
}

</script>
<style lang="less" scoped>
  .image-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .img-box {
    position: relative;
    .select {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 24px;
      height: 24px;
      background-color: #67c23a;
      z-index: 999;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .el-image {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.my-vertical-align {
  display: flex;
  align-items: center;
  gap:5px
}
.btns{
  padding: 7px 10px;
  background-color: #fff;
}
</style>